<?php
/**
 * Created by PhpStorm.
 * User: rain
 * Date: 2018/4/5
 * Time: 下午4:51
 */

namespace App\Http\Controllers\Api;


use App\Models\MemberPrices;
use App\Models\Orders;
use App\Services\OrderService;
use App\Models\Users;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Overtrue\LaravelWeChat\Facade as EasyWeChat;

class OrderController extends AuthorizedController
{
    protected $orderService;

    public function __construct(OrderService $orderService)
    {
        $this->orderService = $orderService;

    }

    public function price(Request $request)
    {
        $prices = MemberPrices::query()->orderBy('sort', 'asc')->get();

        /** @var \App\User $user */
        $user = $request->apiUser;
        $bookId = (int)$request->get('book_id', 0);

        $booPrice = $this->orderService->bookPrice($user->id, $bookId);

        return $this->success([
            'prices' => $prices,
            'book_price' => $booPrice
        ]);
    }


    public function create(Request $request)
    {

        $rules = [
            'goods_type' => 'required|integer|in:0,1,2',
            'goods_id' => 'required|integer',
        ];

        $validator = Validator::make($request->all(), $rules);
        if ($validator->fails()){
            return $this->error();
        }

        try{

            $goodsType = (int)$request->get('goods_type', 0);
            $goodsId = (int)$request->get('goods_id', 0);
            $bookId = (int)$request->get('book_id', 0);
            /** @var \App\User $user */
            $user = $request->apiUser;
            /** @var \App\Models\Orders $order */
            $order = $this->orderService->create($user, $goodsType, $goodsId,$bookId, Orders::PAY_TYPE_MINI_WX);

            $payment = EasyWeChat::payment();

            $data = [
                'body' => $order->title,
                'out_trade_no' => $order->order_code,
                'total_fee' => $order->price,
                'trade_type' => 'JSAPI',
                'openid' => $user->open_id,
            ];

            //开发环境直接支付成功
            if (env('APP_ENV', 'local') == 'produce'){
                //OrderService::pay($order->order_code, Uuid::uuid1(), $config);
                $unify = $payment->order->unify($data);
                Log::info('支付日志', $unify);
                $prepayId = $unify['prepay_id'];
                $order->prepay_id = $prepayId;
                $order->save();

                $config = $payment->jssdk->sdkConfig($prepayId);
            }
            $config['order_code'] = $order->order_code;


            return $this->success(['config' => $config]);
        }catch(\Exception $e){
            return $this->error($e->getMessage());
        }

    }


    public function result(Request $request)
    {
        $rules = [
            'order_code' => 'required|string',
        ];

        $validator = Validator::make($request->all(), $rules);
        if ($validator->fails()){
            return $this->error();
        }

        $order = Orders::where([
            'order_code' => $request->order_code,
            'user_id' => $request->apiUser->id
        ])->select(['order_code', 'status'])->first();

        return $this->success(['order' => $order]);
    }


    public function notify()
    {
        $payment = EasyWeChat::payment();
        $response = $payment->handlePaidNotify(function ($message, $fail){
            Log::info('===weixin_notify===' . json_encode($message));
            // 使用通知里的 "微信支付订单号" 或者 "商户订单号" 去自己的数据库找到订单
            /** @var Orders $order */
            $order = Orders::where(['order_code' => $message['out_trade_no']])->first();

            if (!$order || $order->status != Orders::STATUS_INIT){
                // 如果订单不存在 或者 订单已经支付过了
                return true; // 告诉微信，我已经处理完了，订单没找到，别再通知我了
            }

            if ($message['return_code'] === 'SUCCESS'){ // return_code 表示通信状态，不代表支付状态
                if ($order->price != $message['total_fee']){
                    return true;
                }
                // 用户是否支付成功
                if (array_get($message, 'result_code') === 'SUCCESS'){
                    OrderService::pay($order->order_code, $message['transaction_id'], $message);
                    // 用户支付失败
                }elseif (array_get($message, 'result_code') === 'FAIL'){

                }
            }else{
                return $fail('通信失败，请稍后再通知我');
            }

            return true; // 返回处理完成
        });

        $response->send();
    }


}
